<?php

namespace app\service;

use app\exception\ErrnoPlus;
use app\model\P2pUpgradeSelectorModel;
use share\exception\ApiException;
use share\service\BaseModelService;

class P2pUpgradeSelectorService extends BaseModelService
{

    public static function getModel()
    {
        return new P2pUpgradeSelectorModel;
    }

    /**
     * 编辑条目 新增或者修改
     */
    public static function edit($info)
    {
        $id = $info['id'];
        unset($info['id']);
        if ($id == 0) {
            self::addP2pUpgradeSelector($info);
        } else {
            self::updateP2pUpgradeSelector($id, $info);
        }   
        P2pUpgradeService::deleteCache(); 
        return $info;
    }

    /**
     * 新增条目
     */
    public static function addP2pUpgradeSelector($info)
    {
        $info['priority'] = self::getPriority($info);
        self::add($info);
    }


    /**
     * 修改条目
     */
    public static function updateP2pUpgradeSelector($id, $info)
    {
        $origin  = self::getBase($id);
        if (empty($origin)) {
            throw new ApiException("origin data is not exists", ErrnoPlus::COMMON_INVALID_INPUT);
        }
        $info['priority'] = self::getPriority($info);
        self::update($id, $info);
    }

    
    public static function getPriority($info){
        $priority = 1;
        if(isset($info['dn']) && $info['dn'] !== '' && $info['dn'] !== '*'){
            $priority += 5;
        }

        if(isset($info['sn']) && $info['sn'] !== '' && $info['sn'] !== '*'){
            $priority += 3;
        }

        if(isset($info['pk']) && $info['pk'] !== '' && $info['pk'] !== '*'){
            $priority += 1;
        }
        return $priority;
    }

    /**
     * 删除条目
     */
    public static function delById($id)
    {
        $origin = self::getBase($id);
        if (empty($origin)) {
            return;
        }    
        $res = self::del($id);
        P2pUpgradeService::deleteCache();
        return $res;
    }

    /**
     * 页面查询条件
     */
    public static function buildCondition($filter)
    {
        $res = [];
        if (isset($filter['name']) && !empty($filter['name'])) {
            $res['name'] = ['like', '%' . $filter['name'] . '%'];
        }
        if (isset($filter['dn']) && !empty($filter['dn'])) {
            $res['dn'] = ['like', '%' . $filter['dn'] . '%'];
        }

        if (isset($filter['sn']) && !empty($filter['sn'])) {
            $res['sn'] = ['like', '%' . $filter['sn'] . '%'];
        }

        if (isset($filter['pk']) && !empty($filter['pk'])) {
            $res['pk'] = ['like', '%' . $filter['pk'] . '%'];
        }

        if (isset($filter['p2p_upgrade_conf_id']) && !empty($filter['p2p_upgrade_conf_id'])) {
            $res['p2p_upgrade_conf_id'] = $filter['p2p_upgrade_conf_id'];
        }
  
        return $res;
    }
}
